<template>
  <el-dialog
    v-if="dialogShow"
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="false"
    custom-class="mydialog"
    width="50%"
    style="min-width: 860px;"
    :title="titleContent"
  >
    <el-form
      ref="formRef"
      class="myForm"
      :model="formData"
      :inline="true"
      :label-width="formLabelWidth"
      size="small"
      :rules="formRules"
    >
      <el-form-item
        label="产品名称"
        style="width: 47%; margin-right: 0px;"
      >
        <my-tooltip
          :content="getProductName(productDetail)"
          :is-link="false"
        />
      </el-form-item>
      <el-form-item
        v-if="types==='edit'"
        label="价格编号"
        style="width: 47%; margin-right: 0px;"
      >
        <div class="product-no">{{ formData.priceNumber }}</div>
      </el-form-item>
      <el-form-item
        class="form-item"
        label="准入模式"
        prop="accessMode"
        style="width: 47%; margin-right: 0px;"
      >
        <el-select
          v-model="formData.accessMode"
          style="width: 100%"
          clearable
          filterable
          placeholder="请选择准入模式"
        >
          <el-option
            v-for="(itm, idx) in accessModeOptions"
            :key="itm.id"
            :label="itm.label"
            :value="itm.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        class="form-item"
        label="价格属性"
        prop="priceType"
        style="width: 47%;margin-right: 0px;"
      >
        <el-select
          v-model="formData.priceType"
          style="width: 100%"
          clearable
          filterable
          placeholder="请选择价格属性"
        >
          <el-option
            v-for="(itm, idx) in priceTypeOptions"
            :key="itm.id"
            :label="itm.label"
            :value="itm.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        class="form-item"
        label="适用地区"
        prop="area"
        style="width: 47%; margin-right: 0px;"
      >
        <el-cascader
          ref="cascader"
          v-model="formData.area"
          :popper-append-to-body="false"
          style="width: 100%;"
          :options="citys"
          placeholder="请选择适用地区"
          :props="{ multiple: true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
          collapse-tags
          clearable
          @change="areaChange"
        />
      </el-form-item>
      <el-form-item
        class="form-item"
        label="适用终端"
        prop="terminalType"
        style="width: 47%; margin-right: 0px;"
      >
        <el-select
          v-model="formData.terminalType"
          style="width: 100%"
          clearable
          filterable
          placeholder="请选择适用终端"
        >
          <el-option
            v-for="(itm, idx) in terminalTypeOptions"
            :key="itm.id"
            :label="itm.label"
            :value="itm.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        class="form-item"
        label="市场价"
        prop="marketPrice"
        style="width: 47%; margin-right: 0px;"
      >
        <div class="scj-form-item">
          <el-input
            v-model="formData.marketPrice"
            style="width: 100%"
            clearable
            disabled
            placeholder="请输入市场价"
            oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
            @blur="()=>formData.marketPrice = Number(formData.marketPrice)"
          >
            <template #append>
              <div><span>元</span><span v-if="productDetail.sellUnit"> / {{ getLabel('sell_unit', productDetail.sellUnit) }}</span></div>
            </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item
        class="form-item"
        label="终端价"
        prop="terminalPrice"
        style="width: 47%; margin-right: 0px;"
      >
        <div class="scj-form-item">
          <el-input
            v-model="formData.terminalPrice"
            style="width: 100%"
            clearable
            placeholder="请输入终端价"
            @input="formData.terminalPrice=formData.terminalPrice.replace(/^\.+|[^\d.]/g,'')"
          >
            <template #append>
              <div><span>元</span><span v-if="productDetail.sellUnit"> / {{ getLabel('sell_unit', productDetail.sellUnit) }}</span></div>
            </template>
          </el-input>
        </div>
      </el-form-item>
      <!--
        <el-form-item
          class="form-item"
          label="价格来源"
          prop="priceSource"
          style="width: 47%; margin-right: 0px;"
        >
          <el-select
            v-model="formData.priceSource"
            style="width: 100%"
            clearable
            filterable
            disabled
            placeholder="请选择价格来源"
          >
            <el-option
              v-for="(itm, idx) in priceSourceOptions"
              :key="itm.id"
              :label="itm.label"
              :value="itm.value"
              disabled
            />
          </el-select>
        </el-form-item>
        <el-form-item
          class="form-item"
          label="价格来源描述"
          prop="priceSourceDesc"
          style="width: 47%; margin-right: 0px;"
        >
          <el-input
            v-model="formData.priceSourceDesc"
            placeholder="请输入价格来源描述"
          />
        </el-form-item>
      -->
      <el-form-item
        class="form-item"
        label="底价"
        prop="guidingPrice"
        style="width: 47%; margin-right: 0px;"
      >
        <div class="scj-form-item">
          <el-input
            v-model="formData.guidingPrice"
            style="width: 100%"
            clearable
            placeholder="请输入底价"
            @input="formData.guidingPrice=formData.guidingPrice.replace(/^\.+|[^\d.]/g,'')"
          >
            <template #append>
              <div><span>元</span><span v-if="productDetail.sellUnit"> / {{ getLabel('sell_unit', productDetail.sellUnit) }}</span></div>
            </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item
        label="附件"
        style="width: 100%;"
        prop="attachFiles"
      >
        <upload-file-view
          ref="fileUploadRef"
          :file-arr="formData.attachFiles"
          is-upload
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          style="margin-right: 20px;"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          :loading="btnLoading"
          @click="confirm"
        >提交审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  inject,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { crmStore } from '@CRM/store'
import area from '@/utils/area.js'

export default defineComponent({
  name: 'CreateProductPrice',
  emits: ['createEditSuccess'],
  setup(props, context) {
    const citys = area
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    const formRef = ref(null)
    var cascader = ref(null)
    var fileUploadRef = ref(null)
    var dialogType = ref('create')
    var titleContent = ref('新建产品价格')
    var detailData = reactive({
      btnLoading: false,
      productDetail: {},
      priceTypeOptions: [],
      accessModeOptions: [],
      terminalTypeOptions: [],
      priceSourceOptions: [],
      formData: {
        productId: 0,
        accessMode: '',
        priceType: '',
        region: [],
        area: [],
        terminalType: '',
        marketPrice: '',
        terminalPrice: '',
        priceSource: 'price_source',
        priceSourceDesc: '',
        attachFiles: [],
      },
    })
    const terminalPricePass = (rule, value, callback) => {
      if (value) {
        if (Number(value) > 0) {
          detailData.formData.terminalPrice = Number(value)
          callback()
        } else {
          callback(new Error('终端价必须大于0'))
        }
      } else {
        callback(new Error('请输入终端价'))
      }
    }
    const guidingPricePass = (rule, value, callback) => {
      if (value) {
        if (Number(value) <= detailData.formData.terminalPrice) {
          detailData.formData.guidingPrice = Number(value)
          callback()
        } else {
          callback(new Error('底价不能大于终端价'))
        }
      } else {
        callback(new Error('请输入底价'))
      }
    }
    var formRules = reactive({
      accessMode: [
        {
          required: true,
          message: '请选择准入模式',
          trigger: 'change',
        },
      ],
      priceType: [
        {
          required: true,
          message: '请选择价格属性',
          trigger: 'change',
        },
      ],
      area: [
        {
          required: true,
          message: '请选择适用地区',
          trigger: 'change',
        },
      ],
      terminalType: [
        {
          required: true,
          message: '请选择适用终端',
          trigger: 'change',
        },
      ],
      marketPrice: [
        {
          required: true,
          message: '请输入市场价',
          trigger: 'blur',
        },
      ],
      terminalPrice: [
        {
          required: true,
          validator: terminalPricePass,
          trigger: 'blur',
        },
        {
          pattern:
            /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入数字,可保留两位小数',
        },
      ],
      guidingPrice: [
        {
          required: true,
          validator: guidingPricePass,
          trigger: 'blur',
        },
        {
          pattern:
            /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入数字,可保留两位小数',
        },
      ],
      priceSource: [
        {
          required: false,
          message: '请选择价格来源',
          trigger: 'change',
        },
      ],
      priceSourceDesc: [
        {
          required: false,
          message: '请输入价格来源描述',
          trigger: 'blur',
        },
      ],
      attachFiles: [],
    })
    var formLabelWidth = ref(120)
    var dialogShow = ref(false)
    const open = (types, detail) => {
      dialogType.value = types
      detailData.productDetail = detail.productDetail
      detailData.formData.productId = detail.productDetail.id
      detailData.formData.marketPrice = detail.productDetail.marketPrice

      if (dialogType.value === 'create') {
        titleContent.value = '新建产品价格'
      } else if (dialogType.value === 'edit') {
        titleContent.value = '编辑产品价格'
        detailData.formData = detail.priceDetail
        detailData.formData.area = currentInstance.proxy.getCascaderAreaData(
          detail.priceDetail.region
        )
      }

      detailData.priceTypeOptions =
        crmStore.getters['dictionary/getDictionary']['price_type']
      detailData.accessModeOptions =
        crmStore.getters['dictionary/getDictionary']['access_mode']
      detailData.terminalTypeOptions =
        crmStore.getters['dictionary/getDictionary']['app_mode']
      detailData.priceSourceOptions =
        crmStore.getters['dictionary/getDictionary']['price_source']

      dialogShow.value = true
    }
    const close = () => {
      formRef.value.clearValidate()
      formRef.value.resetFields()
      detailData.productDetail = null
      dialogShow.value = false
    }
    const areaChange = (val) => {
      console.log(val, cascader.value.getCheckedNodes())
      detailData.formData.region = currentInstance.proxy.getServeAreaData(
        val,
        cascader.value.getCheckedNodes()
      )
    }
    const createProductPrice = () => {
      detailData.btnLoading = true
      api.product.CREATE_PRODUCT_PRICE(detailData.formData).then((res) => {
        if (res.code === 0) {
          context.emit('createEditSuccess')
          currentInstance.proxy.customMessage({
            message: '创建成功',
            type: 'success',
          })
          close()
        } else {
          currentInstance.proxy.customMessage({
            message: res.msg,
            type: 'error',
          })
        }
        detailData.btnLoading = false
      })
    }
    const editProductPrice = () => {
      detailData.btnLoading = true
      api.product.EDIT_PRODUCT_PRICE(detailData.formData).then((res) => {
        if (res.code === 0) {
          context.emit('createEditSuccess')
          currentInstance.proxy.customMessage({
            message: '编辑成功',
            type: 'success',
          })
          close()
        } else {
          currentInstance.proxy.customMessage({
            message: res.msg,
            type: 'error',
          })
        }
        detailData.btnLoading = false
      })
    }
    const confirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          if (dialogType.value === 'create') {
            createProductPrice()
          } else if (dialogType.value === 'edit') {
            editProductPrice()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }

    return {
      citys,
      formRef,
      fileUploadRef,
      cascader,
      titleContent,
      ...toRefs(detailData),
      formRules,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
      areaChange,
    }
  },
})
</script>

<style lang="scss" scoped>
.myForm {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;

  .form-item {
    width: 47%;
  }
}
</style>
